<template>
  <div class="app-container">
    <!-- <div style="text-align: center;margin: 20px 0;font-size: 24px;color: #666;">
            <b>样衣报表（按照店铺维度）</b>
        </div> -->
    <el-card>
      <el-row :gutter="20">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <!-- <el-form-item label="店铺编号" prop="shopId">
        <el-input v-model="queryParams.shopId" placeholder="请输入店铺编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->

          <el-col :span="15">
            <el-form-item label="" prop="shopName">
              <!-- <el-input v-model="queryParams.shopName" placeholder="请输入店铺名称" clearable
                                @keyup.enter.native="handleQuery" /> -->
              <el-select
                v-model="queryParams.shopName"
                placeholder="店铺名称"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.sys_product_live"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item prop="productNo" label="">
                            
                            <el-select v-model="queryParams.productNo" clearable filterable remote :remote-method="getDatas"
                                placeholder="款式" style="width:150px">
                                <el-option v-for="item in options" :key="item" :label="item" :value="item">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                        </el-form-item> -->
          </el-col>
        </el-form>
        <!-- <el-col :span="8"> -->
        <!-- <div style="margin: 20px 0;"> 
                
            返回
/** 店铺编号 */
@Excel(name = "店铺编号")
private Long shopId;

/** 店铺名称 */
@Excel(name = "店铺名称")
private String shopName;

/** 销售总额 */
@Excel(name = "销售总额")
private Integer salesAmountTotal;

/** 款式总数 */
@Excel(name = "款式总数")
private Integer productNoTotal;

/** 销售总件数 */
@Excel(name = "销售总件数")
private Integer salesQtyTotal;
            -->
        <timeSearch
          @getDateArr="getDateArr"
          @changDay="changDay"
          :timeArr="timeArr"
          :dayActive="this.dayActive"
          :dayLimit="1095"
        />
        <!-- <Year :curData="curData" ref="resetCommon" @child="child"></Year> -->

        <div style="background-color: #f8f8f9">
          <el-col class="header" :span="4">
            <img
              style="object-fit: contain; width: 50px; height: 50px"
              src="@/assets/day/人群管理.png"
            />
            <div>
              销售总额<br />￥{{ orderTalentDwdTotal.salesAmountTotal }}
            </div>
          </el-col>
          <el-col class="header" :span="4"
            ><img
              style="object-fit: contain; width: 50px; height: 50px"
              src="@/assets/day/款式总数.png"
            />
            <div>款式总数<br />{{ orderTalentDwdTotal.productNoTotal }}</div>
          </el-col>
          <el-col class="header" :span="4"
            ><img
              style="object-fit: contain; width: 50px; height: 50px"
              src="@/assets/day/特卖_选中.png"
            />
            <div>销售总件数<br />{{ orderTalentDwdTotal.salesQtyTotal }}</div>
          </el-col>
        </div>
      </el-row>
    </el-card>
    <el-row :gutter="10" class="mb8">
      <!-- <div style="text-align: center;margin: 20px 0;font-size: 24px;color: #666;">
                    <b>总览（按照店铺维度）</b>

                </div> -->

      <!-- <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                v-hasPermi="['system:user:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                v-hasPermi="['system:user:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                v-hasPermi="['system:user:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
                v-hasPermi="['system:user:import']">导入</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                v-hasPermi="['system:user:export']">导出</el-button>
            </el-col> -->
      <el-col :span="1.5" style="display: none">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:ods:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button> -->
      </el-col>

      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>
    <div ref="tableDom">
      <el-table
        v-loading="loading"
        :maxHeight="orderTalentDwdList.length ? tableHeight : 'auto'"
        :data="orderTalentDwdList"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <!-- <el-table-column label="ID" align="center" prop="id" />
            <el-table-column label="店铺编号" align="center" prop="shopId" /> -->
        <el-table-column label="店铺名称" align="center" prop="shopName" />

        <el-table-column label="合作款式" align="center" prop="productNo"
          ><template slot-scope="scope">
            <div>{{ scope.row.productNo }}</div>
            <div
              style="
                color: rgb(37, 137, 255);
                cursor: pointer;
                text-decoration: underline;
              "
              @click="contact(scope.row)"
            >
              款式维度
            </div>
          </template>
        </el-table-column>
        <el-table-column label="款式主图" align="center" prop="picUrl">
          <!-- <template slot-scope="scope">
              <image-preview :src="scope.row.picUrl" :width="50" :height="50" />
            </template> -->
          <template #default="scope">
            <image-preview :src="scope.row.picUrl" :width="80" :height="80" />
            <!-- <el-popover effect="light" trigger="click" placement="right" width="auto" v-if="scope.row.picUrl">
                            <template #default>
                                <img :src='pjtUrl + scope.row.picUrl'
                                    style="width: 800px;height: 600px;object-fit: contain;" lazy>
                            </template>
                            <template #reference>
                                <img :src='pjtUrl + scope.row.picUrl' style="object-fit: contain;width: 80px; height: 80px"
                                    lazy />
                            </template>
                        </el-popover> -->
          </template>
        </el-table-column>
        <el-table-column label="销售件数" align="center" prop="qtyNum" />
        <el-table-column label="销售额" align="center" prop="amountNumStr" />
        <el-table-column
          label="销售占比"
          align="center"
          prop="amountPercentStr"
        />
        <!-- <el-table-column label="发货日期" align="center" prop="sendDate" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.sendDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="发货日期" align="center" prop="sendDay" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.sendDay, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="支付时间" align="center" prop="payDate" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.payDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column> -->
        <!-- <el-table-column label="支付日期" align="center" prop="payDay" width="180">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.payDay, '{y}-{m}-{d}') }}</span>
                    </template>
                </el-table-column> -->
        <!-- <el-table-column label="已寄出数量" align="center" prop="sendedNum" />
                <el-table-column label="已退回数量" align="center" prop="returnedNum" /> -->
        <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['product:orderTalentDwd:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['product:orderTalentDwd:remove']">删除</el-button>
                </template>
            </el-table-column> -->
      </el-table>
    </div>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>
  
<script>
import {
  listTemplate,
  getTemplate,
  delTemplate,
  addTemplate,
  updateTemplate,
  addTemplateAndSecondry,
  addProNoColorSize,
  productNoLike,
} from "@/api/product/template";
import timeSearch from "./day.vue";
import {
  listOds,
  getOds,
  delOds,
  addOds,
  updateOds,
  sampleOrderTalentDwdByDate,
  sampleOrderTalentDwdTotal,
  sampleOrderTalentProductNoDwdSum,
  sampleOrderTalentProductNoTotal,
} from "@/api/sample/ods";

export default {
  name: "Applydwd",
  dicts: ["sys_product_live"],
  components: { timeSearch },
  data() {
    return {
      options: [],
      pjtUrl: process.env.VUE_APP_BASE_API,
      //总览
      orderTalentDwdTotal: {},
      tableHeight: "",
      dayActive: 2,
      timeArr: [
        { value: "2", label: "昨天" },
        { value: "7", label: "最近7天" },
        { value: "30", label: "最近30天" },
        { value: "365", label: "最近一年" },
        { value: "1", label: "日" },
      ],
      timeGap: { startTime: "", endTime: "" },
      // 达人维度信息表格数据
      orderTalentDwdList: [],
      // 订单来源信息表格数据
      odsList: [],
      applyList: [],
      // 样衣寄样细节数据层表格数据
      applydwdList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // // 用户导入参数
      // upload: {
      //     // 是否显示弹出层（用户导入）
      //     open: false,
      //     // 弹出层标题（用户导入）
      //     title: "",
      //     // 是否禁用上传
      //     isUploading: false,
      //     // 是否更新已经存在的用户数据
      //     updateSupport: 0,
      //     // 设置上传的请求头部
      //     headers: { Authorization: "Bearer " + getToken() },
      //     // 上传的地址
      //     url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      // },
      // 查询参数
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopId: null,
        shopName: "VFU-抖音小店",
        qty: null,
        amount: null,
        referrerName: null,
        referrerId: null,
        sendDate: null,
        sendDay: null,
        payDate: null,
        payDay: null,
        sendedNum: null,
        returnedNum: null,
        payStartDate: null,
        payEndDay: null,
        sendDateStart: null,
        sendDateEnd: null,
        productNo: null,
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    // this.getlistApplydwd()
    // this.getList();
    //   this.getDeptTree();
    //   this.getConfigKey("sys.user.initPassword").then(response => {
    //     this.initPassword = response.msg;
    //   });
  },
  mounted() {
    var _this = this;
    this.resizeTable();
    window.onresize = function () {
      _this.resizeTable();
    };
  },
  //记得清空  如果在keepalive中 则使用activated  deactivated
  destroyed() {
    window.onresize = null;
  },
  methods: {
    /* 获取货号列表 */
    getDatas(key) {
      console.log(JSON.stringify(key));
      this.loading = true;
      // return
      productNoLike(key).then((res) => {
        this.loading = false;
        this.options = res.data;
        console.log(JSON.stringify(this.options));
      });
    },
    //款式维度
    contact(row) {
      console.log(JSON.stringify(row));
      this.$router.push({
        path: "/sample/productNoDwd",
        query: { productNo: row.productNo },
      });
    },

    //时间控件
    changDay(val) {
      this.dayActive = val;
      this.timeGap.startTime = val[0];
      this.timeGap.endTime = val[1];
    },
    getDateArr(value) {
      this.timeGap.startTime = value[0];
      this.timeGap.endTime = value[1];
      console.log(JSON.stringify(this.timeGap));
      const obj = {
        payStartDate: this.timeGap.startTime,
        payEndDay: this.timeGap.endTime,
        shopName: this.queryParams.shopName,
      };
      sampleOrderTalentProductNoDwdSum(obj).then((response) => {
        this.orderTalentDwdList = response.rows;
        console.log(JSON.stringify(response.rows));

        this.total = response.total;
        this.loading = false;
      });

      //总览
      const time = {
        startDate: this.timeGap.startTime,
        endDate: this.timeGap.endTime,
      };
      sampleOrderTalentProductNoTotal(time).then((response) => {
        this.orderTalentDwdTotal = response[0] ? response[0] : {};
        console.log(JSON.stringify(response[0]));
      });
      var timeGap = { dayActive: this.dayActive, ...this.timeGap };
      localStorage.setItem("timeGap", JSON.stringify(timeGap));
      this.dayActive = 1;
    },
    child(objArgu, weekTime) {
      this.objArgu = objArgu;
      this.params.queryType = objArgu.cType;
      this.params.startDate = objArgu.beginTime;
      this.params.endDate = objArgu.endTime;
      this.weekTime = weekTime;
      console.log(JSON.stringify(this.params));
      if (this.params.queryType == 1) {
        const obj = {
          startDate: this.params.startDate,
          endDate: this.params.endDate,
          shopName: this.queryParams.shopName,
        };
        sampleOrderTalentDwdByDate(obj).then((response) => {
          console.log(JSON.stringify(response.rows));
          this.orderTalentDwdList = response.rows;

          this.total = response.total;
          this.loading = false;
        });

        //总览
        sampleOrderTalentDwdTotal(obj).then((response) => {
          this.orderTalentDwdTotal = response[0];
          console.log(JSON.stringify(response[0]));
        });

        // this.$modal.msgWarning('请选择 按年 方式')
        // return
      }
      if (this.params.queryType == 3) {
        // console.log(1);
        const obj = {
          startDate: this.params.startDate,
          endDate: this.params.endDate,
          shopName: this.queryParams.shopName,
        };
        sampleOrderTalentDwdByDate(obj).then((response) => {
          this.orderTalentDwdList = response.rows;
          console.log(JSON.stringify(response));
          this.total = response.total;
          this.loading = false;
        });
        //总览
        sampleOrderTalentDwdTotal(obj).then((response) => {
          this.orderTalentDwdTotal = response[0];
          console.log(JSON.stringify(response[0]));
        });
        // selectMonthSampleNum(obj).then(response => {
        //     this.applydwdList = response;
        //     console.log(JSON.stringify(response));
        //     this.total = response.length
        //     this.loading = false;
        // });
      }
    },
    //比重格式-百分号
    battery(row) {
      // return row.shareRate * 100 + "%";
      //  return parseInt(row.shareRate * 100) + '%'
      return Number(row.returnedRatio * 100).toFixed(2) + "%";
    },
    //比重格式-百分号
    returnRatio(row) {
      // return row.shareRate * 100 + "%";
      //  return parseInt(row.shareRate * 100) + '%'
      return Number(row.returnRatio * 100).toFixed(2) + "%";
    },
    //合计行
    addTotal(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }
        if (index === 1) {
          sums[index] = "N/A";
          return;
        }
        // if (index === 3) {
        //   sums[index] = 'N/A';
        //   return;
        // }
        const values = data.map((item) => Number(item[column.property]));

        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += "";
        } else {
          sums[index] = "N/A";
        }

        if (index === 4) {
          var point = sums[3] / sums[2];
          var str = Number(point * 100).toFixed(2);
          str += "%";
          sums[index] = str;
        }
        if (index === 7) {
          var sum = Number(sums[5]) + Number(sums[6]);
          console.log(sum);
          var point = sums[5] / sum;
          var str = Number(point * 100).toFixed(2);
          str += "%";
          sums[index] = str;
        }
      });

      console.log(JSON.stringify(sums));
      return sums;
    },
    /** 查询订单来源信息列表 */
    getList() {
      this.loading = true;
      sampleOrderTalentProductNoDwdSum({
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        productNo: this.queryParams.productNo,
        payStartDate: this.timeGap.startTime,
        payEndDate: this.timeGap.endTime,
      }).then((response) => {
        console.log(JSON.stringify(response.rows));
        this.orderTalentDwdList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        shopId: null,
        shopName: null,
        shopStatus: null,
        outerPayId: null,
        soId: null,
        iId: null,
        skuId: null,
        outerOiId: null,
        qty: null,
        amount: null,
        referrerName: null,
        referrerId: null,
        price: null,
        sendDate: null,
        sendDay: null,
        payDate: null,
        payDay: null,
        chosenChannel: null,
        commission: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单来源信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getOds(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单来源信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateOds(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOds(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除订单来源信息编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOds(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "product/ods/export",
        {
          ...this.queryParams,
        },
        `ods_${new Date().getTime()}.xlsx`
      );
    },
    // table自动高度
    returnTableHeight(ref, bottomOffset) {
      let height = null;
      height =
        window.innerHeight - ref.getBoundingClientRect().top - bottomOffset;
      return height;
    },

    resizeTable() {
      this.$nextTick(() => {
        this.tableHeight = this.returnTableHeight(this.$refs.tableDom, 100);
      }, 0);
    },
  },
};
</script>
<style lang="scss">
.el-select .el-input {
  width: 100% !important;
}

.header {
  display: flex;
  align-items: center;
  height: 75px;
  // justify-content: center;

  // text-align: center;
  font-size: 18px;
  color: #4e5969;
  // border-right: 1px dashed #666; // font-weight: 510;
  background-color: #f8f8f9;
  padding: 10px 0;
  // font-style: italic;
  // font-family: Haettenschweiler // , Helvetica, sans-serif Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif
}
</style>